package org.ktlab.feature;

import java.io.File;
import java.util.Scanner;
import org.ktlab.json.JSONWriter;

public class RawFeatureParser {
	private String[] fearsArray = {"<tngt>", "<chayno>", "<cuop>"
													   , "<giet>", "<hiep>"};
	private String jsonOutfile = "features.json";
	
	public RawFeatureParser() {}
	
	/**
	 * parse features from member's files to json file 
	 * @param fileLocation where locate member's files
	 * @throws Exception
	 */
	public void featureParseFolder(String fileLocation) 
															throws Exception {
		JSONWriter writerJson = new JSONWriter(jsonOutfile);
		File folder = new File(fileLocation);
		
		if(folder.isDirectory()) {
			File[] files = folder.listFiles();
			for(File f:files) {
				Scanner in = new Scanner(f);
				Feature fear= new Feature();
				int count = 0;
				while(in.hasNext()) {
					String line = in.nextLine();
					if(line.startsWith("#")) {
						continue;
					}else {
						if(inArray(line, fearsArray)) {
							if(count!=0) {
								writerJson.write(fear);
							}
							fear.setType(line);
							fear.clearFearList();
							count++;
						}else if(line.compareTo("<end>")==0){
							break;	//End current file, continue next file
						}else {
							if(line.isEmpty()) {
								continue;
							}
							else {
								fear.addFear(line);	
							}
						}
					}
				}
			}	
		}
	}
	
	/**
	 * Check a string 's' in string array 'a'
	 * @param s
	 * @param a
	 * @return true if string s in string array a
	 */
	public boolean inArray(String s, String[] a) {
		for(String i:a) {
			if(i.compareTo(s)==0) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Test
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		RawFeatureParser rfp = new RawFeatureParser();
		rfp.featureParseFolder("/media/STUDYing/A_SResearch/Student2012/DataReview");
		System.out.println("Done!");
	}
}
